package com.atguigu.srpingcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @Author yangjin
 * @Description
 * @Date 2021/6/28/21:32
 **/
@Service
public class HystrixService {

    /**
     * 模拟正常访问
     * @param id
     * @return
     */
    public String paymentInfo_call_ok(Integer id){
        return "线程池：【"+Thread.currentThread().getName()+"】call_success，id:【"+id+"】";
    }

    /**
     *  模拟访问异常
     * @param id
     * @param sleepSecond
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentInfo_call_fail_handler"
            ,commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")})
    public String paymentInfo_call_fail(Integer id,Integer sleepSecond){
        try {
            TimeUnit.SECONDS.sleep(sleepSecond);
            //int num = 10/0;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "线程池：【"+Thread.currentThread().getName()+"】call_fail，id:【"+id+"】，睡眠时间";
    }

    /**
     * 处理异常
     * @param id
     * @return
     */
    public String paymentInfo_call_fail_handler(Integer id,Integer sleepSecond){
        return "线程池：【"+Thread.currentThread().getName()+"】call_fail，id:【"+id+"】，系统繁忙请重试";
    }

    //=========服务熔断=========
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//开启服务熔断功能
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//快照窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//错误率
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id)
    {
        if(id < 0)
        {
            throw new RuntimeException("******id 不能负数");
        }
        String serialNumber = IdUtil.simpleUUID();

        return Thread.currentThread().getName()+"\t"+"调用成功，流水号: " + serialNumber;
    }
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id)
    {
        return "id 不能负数，请稍后再试，/(ㄒoㄒ)/~~   id: " +id;
    }
}
